/*
The MIT License

Copyright (c) 2010 Yuen Ho Wong

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

// TODO: refactor the form into actual objects
var ext = safari.extension;

var suggestionTimer = null;

function sendMessageToGlobalPage (name, data) {
    safari.self.tab.dispatchMessage(name, data);
}

function listenForMessageFromGlobalPage (func) {
    safari.self.addEventListener('message', func, false);
}

function validateForm(form, passFunc) {
    var formElements = form.getElements();

    formElements.forEach(function (element, index, array) {
        if (!element.checkValidity()) {
            var prev = element.previous();
            if (prev === undefined || !prev.hasClassName('safarious-error-message')) {
                var errorMessage = document.createElement('p');
                errorMessage.addClassName('safarious-error-message');
                errorMessage.textContent = element.validationMessage;
                element.insert({
                    before: errorMessage
                });
            }
        }
    });

    if (formElements.every(function (element, index, array) {
        if (element.checkValidity()) {
            var prev = element.previous();                
            if (prev && prev.hasClassName('safarious-error-message')) {
                prev.remove();
            }
            return true;
        }

        return false;
    })) {
        passFunc();
    }    
}

function setupPopupContent(popup) {

    popup.innerHTML = ADD_BOOKMARK_POPUP_HTML;

    var form = popup.down('#safarious-bookmark-form');

    form.down('#safarious-bookmark-form-url').value = document.location.href;
    form.down('#safarious-bookmark-form-description').value = document.title;

    $('safarious-bookmark-form-submit-button').observe('click', function (e) {
        e.stop();

        validateForm(form, function () {
            sendMessageToGlobalPage('addBookmark', form.serialize({
                hash: true,
                submit: false
            }));

            e.target.fire('safarious:closepopup');
        });
    });

    $('safarious-bookmark-form-cancel-button').observe('click', function (e) {
        e.stop();
        e.target.fire('safarious:closepopup');
    });

    form.observe('input', function (e) {
        if (e.target.id === 'safarious-bookmark-form-notes') {
            var counterNode = form.down('#safarious-bookmark-form-notescount>em', 0);
            var notesNode = e.target;
            var maxlength = notesNode.maxLength;
            var length = notesNode.value.length;
            counterNode.textContent = maxlength - length;
        }
        else if (e.target.name === 'tags') {
            new Form.Element.DelayedObserver(e.target, 1, function () {
                sendMessageToGlobalPage('suggest', location.href);
            });
        }
    });
}

function popupBookmarkPage() {

    if ($("safarious-add-bookmark-popup")) {
        return;
    }

    var popup = document.createElement('div').setStyle({ visibility: 'hidden' });
    document.body.insert({ top: popup });
    popup.id = "safarious-add-bookmark-popup";
    setupPopupContent(popup);
    popup.setStyle({
        top: (window.innerHeight - popup.offsetHeight) / 2 + 'px',
        left: (window.innerWidth - popup.offsetWidth) / 2 + 'px'
    });
    popup.setStyle({ visibility: 'visible', display: 'none' });

    document.observe("keyup", function (e) {
        if (popup && popup.visible() && e.keyCode == Event.KEY_ESC) {
            popup.fire('safarious:closepopup');
        }
    });

    popup.appear({
        afterFinish: function (e) {
            $('safarious-bookmark-form-description').focus();
            sendMessageToGlobalPage('login');
        }
    });

}

listenForMessageFromGlobalPage(function (e) {
    switch (e.name) {
    case 'addBookmark':
        popupBookmarkPage();
        break;
    case 'suggestions':
        suggestionTimer = undefined;
        var suggestions = $H(e.message).values().flatten().uniq();
        console.log(suggestions);
        break;
    case 'loggedIn':
        var oauthForm = $('safarious-oauth-verifier-form');
        if (oauthForm) {
            oauthForm.hide();
            oauthForm.remove();
            var popup = $('safarious-add-bookmark-popup');
            popup.down('form input[name="description"]').focus();
        }
        break;
    case 'notLoggedIn':
        var form = $('safarious-oauth-verifier-form');
        Effect.BlindDown(form, {
            fps: 60,
            afterFinish: function (e) {
                form.observe('submit', function (e) {
                    e.stop();
                    validateForm(form, function () {
                        var spinner = new Element('img', {src: safari.extension.baseURI + 'ajax-loader.gif'});
                        $('safarious-oauth-verifier-form-request-code-button').replace(spinner);
                        var verifier = $F(form['oauth-verifier']);
                        sendMessageToGlobalPage('requestAccessToken', verifier);
                    });
                });

                var codeButton = $('safarious-oauth-verifier-form-request-code-button');
                codeButton.observe('click', function (e) {
                    e.stop();
                    sendMessageToGlobalPage('login'); // TODO: kind of a misnomer
                });

                $('safarious-oauth-verifier').focus();
            }
        });
        break;
    case 'setupAddBookmarkShortcut':
        if (e.message) {
            shortcut.add(e.message, popupBookmarkPage);
        }
        break;
    case 'changeAddBookmarkShortcut':
        var oldShortcut = e.message['old'];
        var newShortcut = e.message['new'];
        if (oldShortcut) {
            shortcut.remove(oldShortcut);
        }
        if (newShortcut) {
            shortcut.add(newShortcut, popupBookmarkPage);
        }
        break;
    case 'error': // TODO: display a user friendly error notice
        console.error(e.message);
        break;
    }
}, false);

sendMessageToGlobalPage('getAddBookmarkShortcut');

document.observe('safarious:closepopup', function (e) {
    var popup = $('safarious-add-bookmark-popup');
    if (!popup.safariousPopUpClosing) {
        popup.safariousPopUpClosing = true;
        popup.fade({
            afterFinish: function (e) {
                popup.remove();
            }
        });
    }
});

// Opening up an iframe loads the extension injected resources twice, but since
// Safari doesn't support the File and DOM load and save APIs yet, hence this
// ugly hack.
var ADD_BOOKMARK_POPUP_HTML = '\
<div>\
  <form id="safarious-oauth-verifier-form" action="#" style="display: none;">\
    <fieldset>\
      <legend>Yahoo! Access Code</legend>\
      <ul>\
        <li>\
          <label for="oauth-verifier">Code</label>\
          <input id="safarious-oauth-verifier" required="required" type="text" name="oauth-verifier" /> \
          <a id="safarious-oauth-verifier-form-request-code-button" href="#">Request code</a>\
        </li>\
      </ul>\
    </fieldset>\
  </form>\
  <form id="safarious-bookmark-form" action="#">\
    <fieldset>\
      <legend>Save a Bookmark</legend>\
      <ul>\
        <li>\
          <label for="url">URL</label>\
          <input id="safarious-bookmark-form-url" required="required" type="text" name="url" />\
        </li>\
        <li>\
          <label for="description">TITLE</label>\
          <input id="safarious-bookmark-form-description" required="required" type="text" name="description" />\
        </li>\
        <li>\
          <label for="extended">NOTES</label>\
          <span class="info" id="safarious-bookmark-form-notescount"> <em>1000</em> characters left</span>\
          <textarea id="safarious-bookmark-form-notes" maxlength="1000" name="extended" cols="62" rows="10"></textarea>\
        </li>\
        <li>\
          <label for="tags">TAGS</label>\
          <span class="info"> space separated</span>\
          <input id="safarious-bookmark-form-tags" type="text" name="tags" />\
        </li>\
      </ul>\
    </fieldset>\
    <footer>\
      <div>\
        <input type="checkbox" name="shared" value="no" />\
        <label for="shared"> Mark as private</label>\
      </div>\
      <div>\
        <input id="safarious-bookmark-form-submit-button" name="submit" type="submit" value="Save" /> \
        <a id="safarious-bookmark-form-cancel-button" href="#" >Cancel</a>\
      </div>\
    </footer>\
  </form>\
</div>';
